﻿<template>
	<div
		class="draw"
		ref="draw">
		<div
			id="webgl"
			v-if="isShowWebgl"></div>
	</div>
</template>

<script>
	import * as THREE from "three"; //  三维
	import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; //  控制器

	let scene = new THREE.Scene();
	let controls = null;
	let camera = null;

	export default {
		name: "Draw",
		data() {
			return {
				sightline: {
					scale: 45, //  视线比例
					type: "PerspectiveCamera", //  相机的类型
					posiy: [-5000, 7000, 16000], //  相机位置
				},
			};
		},
		onLoad() {},
		methods: {
			initScene() {
				scene = new THREE.Scene(); //  场景对象Scene
			},
			initRenderer() {
				renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
				//   设置渲染区域尺寸
				renderer.setSize(
					this.$refs.draw.offsetWidth,
					this.$refs.draw.offsetHeight
				);
				//   开启渲染阴影
				renderer.shadowMap.enabled = true;
				renderer.shadowMap.type = THREE.PCFSoftShadowMap;
				renderer.hadowMapEnabled = true;
				//  body元素中插入canvas对象
				this.$refs.draw.appendChild(renderer.domElement);
			},
			//   初始化光源
			initLight() {
				//增加环境光(环境光颜色,环境光强度)
				const ambientLight = new THREE.AmbientLight(0xffffff, 2);
				ambientLight.name = "ambientLight";
				scene.add(ambientLight);

				//增加太阳光
				const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
				directionalLight.name = "directionalLight";
				directionalLight.position.set(8000, 8000, -2000);
			},

			//   初始化相机
			initCamera() {
				const k = this.$refs.draw.offsetWidth / this.$refs.draw.offsetHeight; //  窗口宽高比
				camera = new THREE.PerspectiveCamera(
					this.sightline.scale,
					k,
					1,
					100000
				);
				camera.position.set(
					this.sightline.posiy[0],
					this.sightline.posiy[1],
					this.sightline.posiy[2]
				);
				camera.up.set(0, 1000, 0);
				camera.lookAt(0, 0, 1);
			},
			//   初始化控制
			initOrbitControls() {
				controls = new OrbitControls(camera, renderer.domElement); //  创建控件对象
				controls.target.set(0, 0.5, 0); //控制器轴的方向，Y轴向上
				controls.update(); //控制器更新
			},
			//   设置动画
			animate() {
				if (!renderer) {
					return;
				}
				if (this.count < 2) {
					this.count++;
					renderer.render(scene, camera);
					controls.update();
				}
				if (animateId) cancelAnimationFrame(animateId);
				animateId = requestAnimationFrame(this.animate);
			},
			//   添加全局方法
			addmeth() {
				//   监听窗口尺寸变化
				window.addEventListener("resize", this.changeSize, false);
			},
			//   监听尺寸变化
			changeSize() {
				//   重置渲染器输出画布canvas尺寸
				renderer.setSize(
					this.$refs.draw.offsetWidth,
					this.$refs.draw.offsetHeight
				);
				const k = this.$refs.draw.offsetWidth / this.$refs.draw.offsetHeight; //  窗口宽高比
				//  重置相机投影的相关参数
				camera.aspect = k;
				//   需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
				camera.updateProjectionMatrix();
			},
		},
	};
</script>

<style></style>
